import { computed, ref } from 'vue';
import { defineStore } from 'pinia';

import type { Category } from '@/views/main/components/types';
import { getCategory } from '@/api';
import { CATEGORY_INITIAL_DATA } from '@/constants';

const useCategoryStore = defineStore(
  'category',
  () => {
    // state
    const categories = ref<Category[]>(CATEGORY_INITIAL_DATA);

    // getters
    const categoriesGetter = computed(() => categories.value);

    // action
    const getCategoryData = async () => {
      const res = await getCategory<{
        categorys: Category[];
      }>();

      const { categorys: categoryData } = res;
      const firstCategory = CATEGORY_INITIAL_DATA.slice(0, 1);

      categories.value = [...firstCategory, ...categoryData];
    };

    return { categories, categoriesGetter, getCategoryData };
  },
  {
    persist: [
      {
        pick: ['categories'],
        storage: localStorage
      }
    ]
  }
);

export default useCategoryStore;
